package multithread;

import util.ThreadUtil;

/**
 * @Author: zhangrongqing
 * @Date: 2019/12/19 17:12
 */
//interrupt优雅停机
public class InterruptDemo {
    public static void main(String[] args) {
        Thread threadA = new Thread(new RunnerDemo());
        System.out.println(threadA.getName() + " started!!");
        threadA.start();
        System.out.println(threadA.getName() + " run");
        ThreadUtil.sleep(1000);
        threadA.interrupt();

        RunnerDemo runnerDemo = new RunnerDemo();
        Thread threadB = new Thread(runnerDemo,"ThreadB");
        System.out.println(threadB.getName() + " started!!");
        threadB.start();
        System.out.println(threadB.getName() + " run");
        ThreadUtil.sleep(3000);
        runnerDemo.cancel();
    }
}

class RunnerDemo implements Runnable{
    private boolean on = true;
    private long i;
    @Override
    public void run() {
        while(on && !Thread.currentThread().isInterrupted()){
            i++;
        }
        System.out.println("count i = " + i);
    }

    public void cancel(){
        this.on = false;
    }
}
